package com.tpolteam.tpol.tpol2019.demo.okhttp3;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.tpolteam.tpol.R;
import com.tpolteam.tpol.tpolcore.utils.ToastUtils;

import java.io.IOException;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DiffUtil;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhttpTestActivity extends AppCompatActivity {

    private TextView http_result;
    String url;

    private Handler handler = new Handler();

    private Response response = null;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_okhttp_test);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        http_result = (TextView) findViewById(R.id.http_result);

        url = "https://www.baidu.com";

        http_result.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //                        runHttp(url);
                        //                        postHttp(url, "");
                        postRequest();
                    }
                }).start();
            }
        });

        String imageUrl = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1572401807&di=ed633e14bdebaad165492e4185b3a589&src=http://hbimg.huabanimg.com/d4c620edc7bde8a636e87c0cbf8f04c7f78ba45050f15-Yoqk9H_fw658";
        //        String imageUrl = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2363760124,175546465&fm=26&gp=0.jpg";
        //        String imageUrl = "https://image.baidu.com/search/detail?z=0&ipn=d&word=gif&step_word=&hs=0&pn=0&spn=0&di=10&pi=&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&cs=3762069483%2C2999699238&os=1974584539%2C2840864856&simid=0%2C0&lpn=0&fm=&sme=&cg=&bdtype=0&simics=2363760124%2C175546465&oriquery=&objurl=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F7f29f120cfd3be189d66b9786681803d80c9c79e1fe49e-aQaUGU_fw658&fromurl=ippr_z2C%24qAzdH3FAzdH3Fi7wkwg_z%26e3Bv54AzdH3FrtgfAzdH3Fbm8d0mn80AzdH3F&gsm=&islist=&querylist=&cardserver=1";
        ImageView imageView = findViewById(R.id.image_001);

        Glide.with(this)
             .load(imageUrl)
             .into(imageView);

        DiffUtil.calculateDiff(new DiffUtil.Callback() {
            @Override
            public int getOldListSize() {
                return 0;
            }

            @Override
            public int getNewListSize() {
                return 0;
            }

            @Override
            public boolean areItemsTheSame(int i, int i1) {
                return false;
            }

            @Override
            public boolean areContentsTheSame(int i, int i1) {
                return false;
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        switch (getRequestedOrientation()) {
            case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
                break;
            case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
                break;
            default:
                break;
        }
        super.onConfigurationChanged(newConfig);
    }

    private void runHttp(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            response = client.newCall(request).execute();
            String aa = response.code() + " | " + response.message();
            String result = response.body().string();
            Log.e("xuliangbo", result);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToast(OkhttpTestActivity.this, "result:" + result);
                    http_result.setText("result:" + result);
                }
            });
        } catch (Exception e) {
            ToastUtils.showToast(OkhttpTestActivity.this, "error:" + e.getMessage());
        }
    }

    /**
     * POST提交Json数据
     */
    private void postHttp(String url, String json) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String resu = response.body().string();
                Log.e("xuliangbo", resu + "");
            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            Log.e("xuliangbo", e.toString());
        }

    }

    /**
     * POST提交键值对
     */
    private void postParams(String url, String json) {

        OkHttpClient client = new OkHttpClient();


        FormBody formBody = new FormBody.Builder()
                .add("platform", "android")
                .add("name", "bug")
                .add("subject", "XXXXXXXXXXXXXXX")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String aa = response.body().string();
            }
        } catch (IOException e) {

        }
    }

    private void postRequest() {

        OkHttpClient client = new OkHttpClient();

        FormBody formBody = new FormBody.Builder()
                .add("", "")
                .build();

        final Request request = new Request.Builder()
                .url("https://www.baidu.com/")
                .get()
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    response = client.newCall(request).execute();
                    String aa = response.code() + " | " + response.message();
                    String rrr = aa + " || " + "打印POST响应的数据：" + response.body().string() + "";
                    Log.e("xuliangbo", rrr);

                    if (response.isSuccessful()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                http_result.setText(rrr);
                            }
                        });
                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


}
